package com.android.lovely.admob

import com.android.lovely.api.service.systemService
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.manager.KVStore
import com.android.lovely.manager.WorkStore
import com.android.lovely.user.UserManager
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.withTimeoutOrNull

object AdmobManager {

    private var chatAdTimerJob: Job? = null

    private val _chatAdEnableFlow = MutableSharedFlow<Boolean>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
    val chatAdEnableFlow: SharedFlow<Boolean> get() = _chatAdEnableFlow

    fun init() {
        applicationScope.launchSafety {
            doContinuousOperation {
                WorkStore.getInstance().lovelyAdId = systemService.getAdmobId()
            }
        }
    }

    fun initTimer() {
        val interval = UserManager.userInfo?.adChatPageInterval ?: Int.MAX_VALUE
        if (System.currentTimeMillis() - KVStore.lastChatAdTime >= interval * 1000L) {
            _chatAdEnableFlow.tryEmit(Ad.Chat.enable())
        } else {
            applicationScope.launchSafety {
                delay(interval * 1000 - (System.currentTimeMillis() - KVStore.lastChatAdTime))
                _chatAdEnableFlow.tryEmit(Ad.Chat.enable())
            }
        }
    }

    fun startTimerFlow() {
        KVStore.lastChatAdTime = System.currentTimeMillis()
        chatAdTimerJob?.cancel()
        chatAdTimerJob = applicationScope.launchSafety {
            _chatAdEnableFlow.emit(false)
            val interval = UserManager.userInfo?.adChatPageInterval ?: Int.MAX_VALUE
            delay(interval * 1000L)
            _chatAdEnableFlow.emit(Ad.Chat.enable())
        }
    }
}